package com.wshl.cloudservice.activities;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.gyf.immersionbar.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.wshl.cloudservice.CloudServiceApplication;
import com.wshl.cloudservice.R;
import com.wshl.cloudservice.ui.widget.LoadingDialog;
import com.wshl.cloudservice.ui.widget.RatingBar;
import com.wshl.cloudservice.utils.DialogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import de.hdodenhof.circleimageview.CircleImageView;
import io.agora.rtc.RtcEngine;
import io.agora.rtm.ErrorInfo;
import io.agora.rtm.ResultCallback;


public class CommentActivity extends AppCompatActivity {

    private String token;
    private int star = 5;
    private String avatar;
    private String name;

    private TextView tvkefuname;
    private RadioGroup rd1, rd2, rd3;
    private RatingBar rba;
    private EditText etContent;
    private TextView ttv_commit_comment;
    private CircleImageView headImg;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.white)//设置状态栏颜色为白色
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();
        token = getIntent().getStringExtra("token");
        avatar = getIntent().getStringExtra("avatar");
        name = getIntent().getStringExtra("name");
        initView();
    }

    private void initView() {
        tvkefuname = findViewById(R.id.tv_kefuname);
        rd1 = findViewById(R.id.rg1);
        rd2 = findViewById(R.id.rg2);
        rd3 = findViewById(R.id.rg3);
        rba = findViewById(R.id.star_count);
        etContent = findViewById(R.id.et_content);
        ttv_commit_comment = findViewById(R.id.tv_commit_comment);
        headImg = findViewById(R.id.img_kefu_head);

        if (!TextUtils.isEmpty(avatar)) {
            Glide.with(this).load(CloudServiceApplication.BASEURL + "/upload/" + avatar).into(headImg);
        }

        tvkefuname.setText("请评价" + name + "的服务");
    }


    public void onComment(View view) {

        if ((int) rba.getSelectedNumber() < 1) {
            ToastUtils.showLong("请选择星星数量");
            return;
        }
        int checked1 = rd1.getCheckedRadioButtonId();
        int checked2 = rd2.getCheckedRadioButtonId();
        int checked3 = rd3.getCheckedRadioButtonId();
        RadioButton radioButton1 = findViewById(checked1);
        RadioButton radioButton2 = findViewById(checked2);
        RadioButton radioButton3 = findViewById(checked3);


        comment((String) radioButton1.getTag(), (String) radioButton2.getTag(), (String) radioButton3.getTag());
    }

    private void comment(String a, String b, String c) {
        if (!NetworkUtils.isConnected()) {
            return;
        }
        String params = "token:" + token + ";start:" + (int) rba.getSelectedNumber() + ";business_level:" + a + ";service_attitude:" + b + ";ask_answer:" + c + ";content:" + etContent.getText().toString().trim();
        LogUtils.i(params);
        // ToastUtils.showLong(params);
        ttv_commit_comment.setEnabled(false);
        LoadingDialog.showLoading(this, "正在提交...");
        OkGo.<String>post(CloudServiceApplication.COMMENT)
                .tag(this)
                .params("token", token)
                .params("star", (int) rba.getSelectedNumber())
                .params("business_level", a)
                .params("service_attitude", b)
                .params("ask_answer", c)
                .params("content", etContent.getText().toString().trim())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LoadingDialog.hideLoading();
                        ttv_commit_comment.setEnabled(true);
                        LogUtils.i("评价：" + response.body());

                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {
                                String code = jsonObject.getString("code");
                                switch (code) {
                                    case "200":

                                        new DialogUtils().showCustomdialog(CommentActivity.this, false);
                                        new Handler().postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {


                                                        destroyEngine();
                                                        finish();
                                                    }
                                                });

                                            }
                                        }, 3000);


                                        break;
                                    default:
                                        if (jsonObject.has("msg")) {
                                            ToastUtils.showLong(jsonObject.getString("msg"));
                                        }
                                        break;
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtils.e("评价：" + response.code());
                        LoadingDialog.hideLoading();
                        ttv_commit_comment.setEnabled(true);
                        ToastUtils.showLong("评价失败，错误码：" + response.code() + ";" + response.body());

                    }
                });


    }

    public CloudServiceApplication application() {
        return (CloudServiceApplication) getApplication();
    }

    private void destroyEngine() {
      //  RtcEngine.destroy();

        application().rtmClient().logout(new ResultCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                LogUtils.i("rtm client logout success");
            }

            @Override
            public void onFailure(ErrorInfo errorInfo) {
                LogUtils.i("rtm client logout failed:" + errorInfo.getErrorDescription());
            }
        });
    }
}
